<template>
    <div ref="wrap" class="infinite" @scroll="scroll">
        <slot></slot>
        <p class="bottom" ref="bottom" v-if="noMore">没有更多数据</p>
        <p class="bottom" ref="bottom" v-else><i class="iconfont icon-jiazailoading-A loading equal"></i>加载中</p>
    </div>
</template>
<script>
  export default {
    props: {
      onInfinite: {
        type: Function,
        default: undefined,
        require: true
      },
      auto: {
        default: true
      }
    },
    data () {
      return {
        scrollTop: 0,
        infiniteLoading: false,
        noMore: false,
        page: 1
      }
    },
    async activated () {
      this.$refs.wrap.scrollTop = this.scrollTop
    },
    deactivated () {
      this.scrollTop = this.$refs.wrap.scrollTop
    },
    computed: {

    },
    created () {
      this.infinite()
    },
    methods: {
      // 执行加载操作
      async infinite () {
        if (this.infiniteLoading || this.noMore) return
        // console.log('开始加载')
        this.infiniteLoading = true
        let result
        try {
          result = await this.onInfinite(this.page)
          if (result) {
            this.page++
          } else {
            this.noMore = true
          }
        } catch (e) {
          this.noMore = true
          if (e.name == 'TypeError') {
            console.warn(e)
          } else {
            throw e
          }
        } finally {
          this.infiniteLoading = false
        }
      },
      async reset () {
        document.documentElement.scrollTop = 0
        Object.assign(this, this.$options.data())
        await this.infinite()
      },
      scroll () {
        const {wrap, bottom} = this.$refs
        const bottomTop = bottom.getBoundingClientRect().top
        const wrapBottom = wrap.getBoundingClientRect().bottom
        if (bottomTop <= wrapBottom) {
          this.infinite()
        }
      }
    },
    components: {}
  }
</script>
<style type="text/scss" lang="scss" scoped>
    .infinite {
        overflow-x: hidden;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    .bottom {
        font-size: 16px;
        height: 40px;
        color: #888888;
        display: flex;
        align-items: center;
        justify-content: center;
        i {
            font-size: 16px;
            line-height: normal;
        }
    }

    .loading {
        display: inline-block;
        animation: circle 1s infinite linear;
        margin-right: 5px;
    }

    @keyframes circle {
        0% {
            transform: rotate(0deg);
        }
        100% {
            transform: rotate(360deg);
        }
    }
</style>
